import { createRouter, createWebHistory, Router, RouteRecordRaw, useRoute } from 'vue-router';
import { constantRoutes } from '@/config/router_config/constant_routes/constant_routes';
import { asyncRoutes } from '@/config/router_config/async_routes/async_routes';
import { createApp } from 'vue';
import useUserStore from '@/config/pania_store/module/user_store';
import 'nprogress/nprogress.css';
import { RouteNameEnum, RouteUrlEnum } from '@/config/router_config/router_components';
import { useMenuStore } from '@/config/pania_store/module/menu_store';

/**
 * 获取所有的路由信息
 */
function getAllRoutes (): Array<RouteRecordRaw> {
  return [
    ...constantRoutes,
    ...asyncRoutes
  ];
}
/**
 * 生成移动端专属的router路由
 */
export const router = createRouter({
  history: createWebHistory(),
  routes: getAllRoutes()
});

/**
 * 处理路由
 * @param router 给app装载的路由
 */
function handleRouter (router : Router) {
  // 取出pinia的对应对象
  const userStore = useUserStore();
  const menuStore = useMenuStore();

  menuStore.createMenuListFromRoutes(getAllRoutes());

  router.beforeEach((to, from, next) => {
    const token = userStore.token;
    menuStore.changeActiveMenu(<RouteUrlEnum>to.path);
    // 开始加载动画
    /* NProgress.configure({ showSpinner: false });
    if (to.meta.title) NProgress.start(); */
    // 是登陆接口的话就放行, 不是登录接口的话要判断是否有token
    if (to.name === RouteNameEnum.login) {
      // 如果有token，直接跳转到首页
      if (token) {
        next({ name: RouteNameEnum.homePage });
      } else {
        next();
      }
    } else {
      if (token) {
        next();
      } else {
        next({ name: RouteNameEnum.login });
      }
    }
  });
}

/**
 * 装载vue-router
 * @param app 要装载vue-router的应用
 */
function installVueRouter (app: ReturnType<typeof createApp>):void {
  app.use(router);
  handleRouter(router);
}

export default installVueRouter;
